/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nu.zoom.catonine.desktop;

import java.awt.Cursor;
import java.awt.EventQueue;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JComponent;

import nu.zoom.swing.desktop.Workbench;
import nu.zoom.swing.desktop.WorkbenchListener;

/**
 * Implementation of the delayd cursor switcher. Depends on the zoom.nu desktop
 * to to inform when the application shuts down so that the cursor timer can be
 * cleaned up.
 * 
 * @see WorkbenchListener#close()
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 */
public class DelayedCursorSwitcherImpl implements DelayedCursorSwitcher, WorkbenchListener {
	private boolean cancelled = false;
	private final Timer timer = new Timer(true);
	private final HashMap<JComponent, TimerTask> componentTasks = new HashMap<JComponent, TimerTask>();
	private final int delayTime;

	public DelayedCursorSwitcherImpl(final int delayTime, Workbench workbench) {
		this.delayTime = delayTime;
		workbench.addWorkBenchListener(this);
	}

	@Override
	public synchronized void scheduleWaitCursor(JComponent component) {
		if (!cancelled && (component != null)) {
			if (componentTasks.get(component) == null) {
				CursorWaitTask task = new CursorWaitTask(component);
				timer.schedule(task, delayTime);
				componentTasks.put(component, task);
			}
		}
	}

	@Override
	public synchronized void cancelScheduleAndSetDefaultCursor(JComponent component) {
		TimerTask task = componentTasks.get(component);
		if (task != null) {
			task.cancel();
			componentTasks.remove(component);
		}
		if (component.getCursor().getType() == Cursor.WAIT_CURSOR) {
			component.setCursor(Cursor.getDefaultCursor());
		}
	}

	@Override
	public void start() {
	}

	@Override
	public void visible() {
	}

	@Override
	public synchronized void close() {
		cancelled = true;
		timer.cancel();
	}

	class CursorWaitTask extends TimerTask {

		private final JComponent component;

		public CursorWaitTask(final JComponent component) {
			this.component = component;
		}

		@Override
		public void run() {
			EventQueue.invokeLater(new Runnable() {

				@Override
				public void run() {
					component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
				}
			});
		}
	}

}
